import {
  ApiResponse,
  PaginatedResponse,
  PaginationMeta,
} from './result.interface';

/**
 * 统一响应结果类
 * 基于 NestJS 响应处理实现
 * 与PHP/Java框架保持基本一致的格式，并添加timestamp字段
 * 
 * PHP格式: {data, msg, code}
 * Java格式: {code, msg, data}
 * NestJS格式: {code, msg, data, timestamp} (与Java基本一致，添加timestamp)
 */
export class Result<T = any> {
  public readonly code: number;
  public readonly msg: string;
  public readonly data?: T;
  public readonly timestamp: string;

  constructor(code: number, msg: string, data?: T) {
    this.code = code;
    this.msg = msg;
    this.data = data;
    this.timestamp = new Date().toISOString();
  }

  /**
   * 成功响应
   * 对应PHP: success($msg, $data, $code)
   * 对应Java: Result.success($msg, $data)
   */
  static success<T>(data?: T, msg: string = '操作成功'): ApiResponse<T> {
    return new Result(1, msg, data);
  }

  /**
   * 失败响应
   * 对应PHP: fail($msg, $data, $code)
   * 对应Java: Result.fail($msg, $data)
   */
  static fail(msg: string = '操作失败', data?: any): ApiResponse {
    return new Result(0, msg, data);
  }

  /**
   * 分页响应
   * 对应PHP/Java的分页数据格式
   */
  static paginated<T>(
    data: T[],
    page: number,
    limit: number,
    total: number,
    msg: string = '查询成功',
  ): PaginatedResponse<T> {
    const totalPages = Math.ceil(total / limit);
    const meta: PaginationMeta = {
      page,
      limit,
      total,
      totalPages,
      hasNext: page < totalPages,
      hasPrev: page > 1,
    };

    return {
      code: 1,
      msg,
      data,
      timestamp: new Date().toISOString(),
      meta,
    };
  }

  /**
   * 创建响应
   * 对应PHP: Response::create(['data' => $data, 'msg' => $msg, 'code' => $code])
   * 对应Java: Result.instance($code, $msg, $data)
   */
  static create<T>(
    code: number,
    msg: string,
    data?: T,
  ): ApiResponse<T> {
    return new Result(code, msg, data);
  }

  /**
   * 转换为 JSON
   * 与PHP/Java基本一致，添加timestamp字段
   */
  toJSON(): ApiResponse<T> {
    return {
      code: this.code,
      msg: this.msg,
      data: this.data,
      timestamp: this.timestamp,
    };
  }
}
